package mobi.weq.servlets.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mobi.weq.dao.UserDao;
import mobi.weq.model.User;
import mobi.weq.util.Util;

/**
 * Servlet implementation class RegisterUser
 */
@WebServlet("/user/update")
public class UpdateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = Util.getUserFromSession(request, response);
		if (user != null) {
			User u = new User();
			u.setUserId(user.getUserId());
			u.setUserName(user.getUserName());

			String displayName = request.getParameter("display_name");
			String password = request.getParameter("password");
			String email = request.getParameter("email");
			String ageGroup = request.getParameter("age-group");
			String usingUserFeedback = request.getParameter("using-user-feedback");
			String havingLungProblems = request.getParameter("has-lung-problems");
			String havingHeartProblems = request.getParameter("has-heart-problems");

			u.setDisplayName(displayName);
			u.setPassword(password);
			u.setAgeGroup(ageGroup);
			u.setEmail(email);

			if (usingUserFeedback != null) {
				u.setUsingUserFeedback(usingUserFeedback.equalsIgnoreCase("on"));
			}
			if (havingHeartProblems != null) {
				u.setHavingHeartProblems(havingHeartProblems.equalsIgnoreCase("on"));
			}

			if (havingLungProblems != null) {
				u.setHavingLungProblems(havingLungProblems.equalsIgnoreCase("on"));
			}

			UserDao ud = new UserDao();
			try {
				u = ud.updateUser(u);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			user.setAgeGroup(ageGroup);
			user.setUsingUserFeedback(u.isUsingUserFeedback());
			user.setHavingLungProblems(u.isHavingLungProblems());
			user.setHavingHeartProblems(u.isHavingHeartProblems());
			
			HttpSession session = request.getSession(true);
			session.setAttribute("user", u);
//			response.sendRedirect("../settings");
			response.getWriter().print("{\"message\":\"Updated Successfully\"}");
		}
	}
}
